package com.jmp.autocofiguration.web.interceptor;

import com.jmp.base.dto.LogAddRequest;
import lombok.extern.slf4j.Slf4j;
import one.stand.util.RequestContext;
import one.stand.util.RequestContextHolder;
import org.springframework.context.ApplicationContext;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Objects;

/**
 * @author Administrator
 */
@Slf4j
public class LogOperationInterceptor extends HandlerInterceptorAdapter {
    private ApplicationContext applicationContext;

    public LogOperationInterceptor(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        try {
            if (handler instanceof HandlerMethod) {
                HandlerMethod h = (HandlerMethod) handler;
                LogOperation apiOperation = h.getMethodAnnotation(LogOperation.class);
                RequestContext requestContext = RequestContextHolder.getRequestContext();
                if (Objects.nonNull(apiOperation) && Objects.nonNull(requestContext) && requestContext.isLogin()) {
                    log(requestContext, apiOperation);
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return true;
    }

    private void log(RequestContext requestContext, LogOperation apiOperation) {
        RequestContext.User user = requestContext.getUser();
        Integer userId = user.getUserId();
        Integer companyId = user.getCompanyId();
        LogAddRequest logAddRequest = LogAddRequest.builder()
                .type(apiOperation.type())
                .userId(userId)
                .companyId(companyId)
                .content(apiOperation.value())
                .date(new Date())
                .build();
        LogAddEvent logAddEvent = new LogAddEvent(logAddRequest);
        applicationContext.publishEvent(logAddEvent);
    }
}
